from django.forms.models import model_to_dict
from BloodSpiderAPI.apis.image import utils as image_utils


# 模型转字典
def utils_model_to_dict(model, *args, **kwargs):
    data = model_to_dict(model)
    
    # 处理外键字段
    if hasattr(model, 'uid') and model.uid:
        data['uid'] = {
            'uid': str(model.uid.uid),
            'username': model.uid.username,
        }
    if hasattr(model, 'category') and model.category:
        data['category'] = {
            'cid': str(model.category.cid),
            'name': model.category.name,
        }
    
    # 获取并添加相关联的图片数据
    if hasattr(model, 'images'):
        data['images'] = []
        for image in model.images.all():
            data['images'].append(image_utils.utils_model_to_dict(image))
    
    set_info_js_path = kwargs.get("set_info_js_path", "")
    if set_info_js_path:
        data["set_info_js_path"] = set_info_js_path
    
    return data